package cn.szzsi._web;

import cn.szzsi.common.kit.ReqUrlUtil;
import cn.szzsi.service.UserService;
import cn.szzsi.common.kit.IdGen;


import cn.szzsi.common.kit.SessionUtil;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.Orders;
import cn.szzsi.common.model.SiteConfig;
import com.jfinal.aop.Clear;
import com.jfinal.core.JFinal;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.QrcodeApi;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户推荐二维码
 * Created by yuanzheng on 2016/11/16.
 */
public class QrcodeController extends BaseWebController<Member> {
    private String memberId;
    private String apiid;//应用id
    private String shopId;//店铺id
    private String openid;//
    private String scene_id;//场景id
    private String pid;//通过扫码推荐的用户上级id
    private String pids;///通过扫码推荐的用户所有上级id
    private String GET_QRCODE_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
    //获取二维码
    @Clear
    public void index(){
        Member member=getLoginMember();
        if(member!=null&& StrKit.isBlank(member.getStr("qrcode"))){
            memberId=member.getStr("id");
            String qrcodeUrl=qrcode(memberId,"");
            String logoUrl = member.getStr("headimgurl");
            try {
                String filename = QRCodeUtil.savePic(qrcodeUrl,member.getId()+"_orgin.png","");
                String filelogoname = "";
                if(StrKit.isBlank(logoUrl)){
                    filelogoname = JFinal.me().getServletContext().getRealPath("/")+"/template/wap4/images/defaultlogo.png";
                }else{
                    filelogoname = QRCodeUtil.savePic(logoUrl,member.get("id")+"_logo.png",null);
                }
                String logoOrcode = QRCodeUtil.makeLogoImage(filename,filelogoname,null,true);
                if(StrKit.notBlank(logoOrcode)){
                    qrcodeUrl = logoOrcode;
                }
                member.set("qrcode",qrcodeUrl).update();
            } catch (Exception e) {
                e.printStackTrace();
            }
            redirect(qrcodeUrl);

        }else{
            redirect(member.getStr("qrcode"));
        }
    }

    //用户扫码获取用户信息
    public void getUserInfo(){
        System.out.println("****");
        openid=getPara("openid");
        scene_id=getPara("scene_id");//场景值:格式SC_memberId
        pid=scene_id.replaceAll("SC_","");
        Member pidMember= Member.dao.findById(pid);
        shopId=pidMember.getStr("shopId");//推荐人和被推荐人的shopId相同
        if(!"0".equals(pidMember.getStr("pids"))){
            pids = pidMember.getStr("pids") + "," + pidMember.getStr("id");//本级的pids即为上级的pids+上级的pid
        }else{
            pids = pid;
        }

        Member member= Member.dao.isExistByOpenid(openid);
        if(member==null){//用户不存在
            SiteConfig siteConfig= SiteConfig.getByShopId(shopId);
            apiid=siteConfig.getStr("apiid");
            String reqUrl= ReqUrlUtil.getUserInfo;
            String param="openid="+openid+"&apiid="+apiid;
            String result= HttpKit.post(reqUrl,null,param);
            JSONObject userJson=new JSONObject(result).getJSONObject("data");
            String nickname= StringUtils.defaultIfBlank(userJson.get("nickname").toString(),"-");
            String sex=userJson.get("sex").toString();
            String country=userJson.get("country").toString();
            String province=userJson.get("province").toString();
            String city=userJson.get("city").toString();
            String headimgurl=userJson.get("headimgurl").toString();
            //String privilege=userJson.get("privilege").toString();
            String registerIp=getRequest().getRemoteAddr();
            String code = IdGen.get().nextId(10);
            Member m = Member.saveMemberInfo(pid,pids,openid,nickname,sex,country,province,city,headimgurl,null,null,shopId,registerIp, code);

            //循环发送关注模板消息
            if(StrKit.notBlank(pids)){
                for(String s:pids.split(",")){
                    UserService.us.sendFocusMSG(apiid,s,m);
                }
            }

            Map<String, String> jsonMap = new HashMap<String, String>();
            jsonMap.put(STATUS, SUCCESS);
            jsonMap.put(MESSAGE,"");
            renderJson(jsonMap);
        }else{
            Map<String, String> jsonMap = new HashMap<String, String>();
            jsonMap.put(STATUS, SUCCESS);
            jsonMap.put(MESSAGE, "用户已存在！");
            renderJson(jsonMap);
        }
    }

    public String qrcode(String scene_id, String apiid) {
        String qr = "";
        try {
            ApiConfigKit.setThreadLocalApiConfig(SessionUtil.getApiConfig(apiid));
            ApiResult apiResult = QrcodeApi.createPermanent(scene_id);
            Integer errcode = apiResult.getInt("errcode");
            if (null != errcode && errcode == 40001) {
                apiResult = QrcodeApi.createPermanent(scene_id);
            }
            System.out.println("創建二维码**************" + apiResult);
            qr = apiResult.getStr("ticket");
        } finally {
            ApiConfigKit.removeThreadLocalApiConfig();
        }
        return  GET_QRCODE_URL+qr;
    }

    public void test(){
        Member m = Member.dao.findById("400def63cf5149b7aee2115c6db1f19d");
        Orders o = Orders.dao.findById("04005bb289134d8587519a4ee4d82402");
        UserService.us.sendFocusMSG("C1DFFAD80E4F467B3924BEE2F53ED139",pids,m);
        UserService.us.sendFxMSG("C1DFFAD80E4F467B3924BEE2F53ED139","",o,"25元");
    }

    public static void main(String[] args) {

        System.out.println(StrKit.getRandomUUID());
    }

}
